<template>
  <div class="popup">
    <van-cell-group inset
      ><van-field
        v-if="changeItem == 'password'"
        v-model="oldPassword"
        center
        clearable
        :label="`原密码`"
        placeholder="请输入原密码"
      />
      <van-field
        v-model="message"
        center
        clearable
        :label="`修改${title}`"
        :placeholder="`请输入需要修改的${title}`"
      >
        <template #button>
          <van-button size="small" type="primary" @click="doUpdate">确认修改</van-button>
        </template>
      </van-field>
    </van-cell-group>
  </div>
</template>
<script>
import { reactive, toRefs } from "@vue/reactivity";
import { onBeforeMount } from "@vue/runtime-core";
import { useStore } from "vuex";
import { Toast } from "vant";
export default {
  props: ["title", "changeItem"],
  setup(props) {
    const store = useStore();
    const state = reactive({
      message: "",
      oldPassword: "",
    });
    onBeforeMount(() => {
      console.log();
      console.log(store);
    });
    const doUpdate = async () => {
      const passwordReg = /^[\w_-]{6,16}$/;

      if (state.message == "") {
        Toast("修改输入不能为空！！");
        return;
      }
      if (props.changeItem == "password") {
        if (!passwordReg.test(state.message)) {
          Toast({
            message: "密码是6-16位喔",
            position: "top",
          });
          return;
        }
      }
      await store.dispatch("_updateUserInfo", {
        oldPassword: state.oldPassword || "no",
        changesItemName: props.changeItem,
        data: state.message,
      });
      if (props.changeItem == "password") {
        sessionStorage.setItem("token", "");
        localStorage.setItem("token", "");
        window.location.href = "/";
        return;
      }
      window.location.href = "/setting";
    };
    return { ...toRefs(state), doUpdate };
  },
};
</script>
<style></style>
